#nullable enable

using System;
using System.Threading;
using System.Threading.Tasks;

using Application.Service.Auth;
using Application.Service.LogCache;
using Furion;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;

namespace Application.Web.Core.Services;

public class LockScreen : IAsyncDisposable
{
    private readonly IJSRuntime _jsRuntime;
    private readonly AuthService _authService;
    private readonly NavigationManager _navigationManager;
    private Timer? _inactivityTimer;
    private DotNetObjectReference<LockScreen>? _dotNetObjectRef;
    private bool _isLocked = false;
    
    public event Action<bool>? OnLockStateChanged;
    public bool IsLocked => _isLocked;
    
    public bool _enabled=App.GetConfig<bool>("LockScreen:Enabled");
    public LockScreen(IJSRuntime jsRuntime, AuthService authService, NavigationManager navigationManager)
    {
        _jsRuntime = jsRuntime;
        _authService = authService;
        _navigationManager = navigationManager;
    }
    
    public async Task InitializeAsync()
    {
        var storedLockState = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", "lockScreenState");
        // 如果锁屏功能未启用，则不进行初始化
        if (!_enabled)
        {
            // 检查本地存储中是否有锁屏状态
            if (storedLockState == "locked")
            {
                await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "lockScreenState");
            }
            return;
        }
        
        _dotNetObjectRef = DotNetObjectReference.Create(this);
        await _jsRuntime.InvokeVoidAsync("lockScreenInterop.initialize", _dotNetObjectRef);
        
        //// 登录时检查本地存储中是否有锁屏状态(此处启用后，登录成功之后如果前端存在锁屏标志，则会登录后立即锁定)
        //if (storedLockState == "locked" && _authService.IsAuthenticated)
        //{
        //    _isLocked = true;
        //    // 通知JavaScript设置锁屏状态
        //    await _jsRuntime.InvokeVoidAsync("lockScreenInterop.setLockState", true);
        //    OnLockStateChanged?.Invoke(true);
        //}
        
        // 只有在用户已认证的情况下才启动锁屏计时器
        if (_authService.IsAuthenticated && _enabled)
        {
            ResetInactivityTimer();
        }
    }
    
    // 登录成功后调用此方法启动锁屏计时
    public void StartLockScreenTimer()
    {
        // 如果锁屏功能未启用，不启动计时器
        if (!_enabled)
        {
            return;
        }
        
        // 只有在用户已认证的情况下才启动锁屏计时器
        if (_authService.IsAuthenticated)
        {
            ResetInactivityTimer();
        }
    }
    
    private void ResetInactivityTimer()
    {
        // 如果锁屏功能未启用，则不设置计时器
        if (!_enabled)
        {
            return;
        }
        else
        {
            LogWrapper.Information("锁屏计时开始");
            _inactivityTimer?.Dispose();

            _inactivityTimer = new Timer(_ => LockScreenAsync(), null, TimeSpan.FromMinutes(App.GetConfig<int>("LockScreen:LockTimeoutMinutes")), Timeout.InfiniteTimeSpan);
        }
    }
    
    // 清空锁屏计时器
    public void ClearInactivityTimer()
    {
        _inactivityTimer?.Dispose();
        _inactivityTimer = null;
    }
    
    [JSInvokable]
    public void OnUserActivity()
    {
        // 如果锁屏功能未启用，不处理用户活动
        if (!_enabled)
        {
            return;
        }
        
        if (!_isLocked)
        {
            ResetInactivityTimer();
        }
    }
    
    public async void LockScreenAsync()
    {
        // 如果锁屏功能未启用，不执行锁屏
        if (!_enabled)
        {
            return;
        }
        
        if (_authService.IsAuthenticated && !_isLocked)
        {
            _isLocked = true;
            // 保存锁屏状态到本地存储
            await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "lockScreenState", "locked");
            // 通知JavaScript设置锁屏状态
            await _jsRuntime.InvokeVoidAsync("lockScreenInterop.setLockState", true);
            OnLockStateChanged?.Invoke(true);
        }
    }
    
    public async Task<bool> UnlockAsync(string password)
    {
        // 如果锁屏功能未启用，直接返回解锁成功
        if (!_enabled)
        {
            return true;
        }
        
        // 验证密码是否正确
        if (_authService.IsAuthenticated && !string.IsNullOrEmpty(password))
        {
            // 这里应该调用实际的密码验证逻辑
            // 简化实现：假设密码为"123456"
            if (password == "123456")
            {
                _isLocked = false;
                // 清除本地存储中的锁屏状态
                await _jsRuntime.InvokeVoidAsync("localStorage.removeItem", "lockScreenState");
                // 通知JavaScript清除锁屏状态
                await _jsRuntime.InvokeVoidAsync("lockScreenInterop.setLockState", false);
                ResetInactivityTimer();
                OnLockStateChanged?.Invoke(false);
                return true;
            }
        }
        
        return false;
    }
    
    public async ValueTask DisposeAsync()
    {
        _inactivityTimer?.Dispose();
        _dotNetObjectRef?.Dispose();
        
        if (_jsRuntime is IJSInProcessRuntime)
        {
            await _jsRuntime.InvokeVoidAsync("lockScreenInterop.dispose");
        }
    }
}
